<template>
  <div class="payment-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>企业缴费管理</span>
          <el-button type="primary" @click="handleAdd">添加缴费记录</el-button>
        </div>
      </template>

      <!-- 缴费列表 -->
      <el-table :data="paymentList" style="width: 100%" v-loading="loading">
        <el-table-column prop="type" label="缴费类型" />
        <el-table-column prop="paymentUnit" label="缴费单位" />
        <el-table-column prop="amount" label="缴费金额">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentDate" label="缴费日期" />
        <el-table-column prop="paymentCertification" label="缴费凭证">
          <template #default="{ row }">
            <el-image
                v-if="row.paymentCertification"
                :src="row.paymentCertification"
                :preview-src-list="[row.paymentCertification]"
                fit="cover"
                style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="info">未审核</el-tag>
            <el-tag v-if="row.status === 1" type="success">审核成功</el-tag>
            <el-tag v-if="row.status === 2" type="danger">审核失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" v-if="row.status === 0" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" v-if="row.status === 0" @click="handleDelete(row)">删除</el-button>
            <el-button type="text" v-if="row.status === 1 || row.status === 2" @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        @close="handleDialogClose"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="缴费类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择缴费类型" :disabled="isView">
            <el-option label="房租" value="房租" />
            <el-option label="入驻押金" value="入驻押金" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="缴费单位" prop="paymentUnit"><el-input  v-model="form.paymentUnit"/></el-form-item>
        <el-form-item label="缴费金额" prop="amount">
          <el-input-number
              v-model="form.amount"
              :precision="2"
              :step="100"
              :min="0"
              style="width: 200px"
              :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="缴费日期" prop="paymentDate">
          <el-date-picker
              v-model="form.paymentDate"
              type="date"
              placeholder="选择日期"
              style="width: 200px"
              :disabled="isView"
          />
        </el-form-item>
        <el-form-item label="缴费凭证" prop="paymentCertification">
          <el-upload
              class="upload-demo"
              :http-request="handleUpload"
              :before-remove="handleBeforeRemove"
              :file-list="fileList"
              :disabled="isView"
          >
            <el-button type="primary" :disabled="isView">上传凭证</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png 文件，且不超过 2MB
              </div>
            </template>
          </el-upload>
          <el-image
              v-if="form.paymentCertification"
              :src="form.paymentCertification"
              style="width: 100px; height: 100px; margin-top: 10px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :disabled="isView">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import {ElMessage, ElMessageBox, type FormRules} from 'element-plus';
import type { FormInstance, UploadFile, UploadFiles } from 'element-plus';
import { getLoginUserId } from '@/utils/storage';
import { uploadFile } from '@/api/file';
import { getPaymentList, addPayment, updatePayment, deletePayment } from '@/api/personal-center';
import { convertHttpToHttps} from "@/utils/urlConverter";

interface PaymentForm {
  id?: number;
  type: string;
  amount: number;
  paymentDate: string;
  paymentCertification: string;
  status?: number;
  paymentUnit:string;
}

const loading = ref(false);
const paymentList = ref<any[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref('添加缴费记录');
const formRef = ref<FormInstance>();
const isEdit = ref(false);
const isView = ref(false);

const form = reactive<PaymentForm>({
  type: '',
  paymentUnit: '',
  amount: 0,
  paymentDate: '',
  paymentCertification: '',
  status: 0
});

// 添加文件列表
const fileList = ref<UploadFile[]>([]);

const rules = reactive<FormRules>({
  type: [{ required: true, message: '请选择缴费类型', trigger: 'change' }],
  paymentUnit: [{ required: true, message: '请输入缴费单位（企业名称）', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入缴费金额', trigger: 'blur' }],
  paymentDate: [{ required: true, message: '请选择缴费日期', trigger: 'change' }],
  paymentCertification: [{ required: true, message: '请上传缴费凭证', trigger: 'change' }]
});

// 获取缴费列表
const getPaymentListData = async () => {
  loading.value = true;
  try {
    const res = await getPaymentList();
    paymentList.value = res.data.records;
  } catch (error) {
    console.error('获取缴费列表失败:', error);
    ElMessage.error('获取缴费列表失败');
  } finally {
    loading.value = false;
  }
};

// 添加缴费记录
const handleAdd = () => {
  isEdit.value = false;
  isView.value = false;
  dialogTitle.value = '添加缴费记录';
  dialogVisible.value = true;
};

// 编辑缴费记录
const handleEdit = (row: any) => {
  isEdit.value = true;
  isView.value = false;
  dialogTitle.value = '编辑缴费记录';
  Object.assign(form, row);
  // 设置文件列表
  if (row.paymentCertification) {
    fileList.value = [ {
      name: '缴费凭证',
      url: row.paymentCertification
    }];
  }
  dialogVisible.value = true;
};

// 查看缴费记录
const handleView = (row: any) => {
  isView.value = true;
  dialogTitle.value = '查看缴费记录';
  Object.assign(form, row);
  // 设置文件列表
  if (row.paymentCertification) {
    fileList.value = [ {
      name: '缴费凭证',
      url: row.paymentCertification
    }];
  }
  dialogVisible.value = true;
};

// 删除缴费记录
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这条缴费记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deletePayment( row.id );
      ElMessage.success('删除成功');
      getPaymentListData();
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  });
};


// 处理文件上传
const handleUpload = async (options: any) => {
  const file = options.file;
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!');
    return;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return;
  }

  try {
    const formData = new FormData();
    formData.append('file', file);
    const res = await uploadFile(formData);
    form.paymentCertification =res.data.url ;
    fileList.value = [ {
      name: file.name,
      url: form.paymentCertification
    }];
    ElMessage.success('上传成功');
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage.error('上传失败');
  }
};

// 删除文件
const handleBeforeRemove = async (file: UploadFile, files: UploadFiles) => {
  form.paymentCertification = '';
  fileList.value = [];
  return true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          const data = await updatePayment(form);
          if(data.code === 200){
            ElMessage.success('更新成功');
          }else{
            ElMessage.error(data.msg);
          }
        } else {
          const data = await addPayment(form);
          if(data.code === 200){
            ElMessage.success('添加成功');
          }else{
            ElMessage.error(data.msg);
          }
        }
        dialogVisible.value = false;
        getPaymentListData();
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      }
    }
  });
};

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields();
  form.type = '';
  form.paymentUnit = '';
  form.amount = 0;
  form.paymentDate = '';
  form.paymentCertification = '';
  fileList.value = [];
  isEdit.value = false;
  isView.value = false;
};

onMounted(() => {
  getPaymentListData();
});
</script>

<style scoped lang="scss">
.payment-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .upload-demo {
    margin-top: 10px;
  }
}
</style>
